# coding=utf-8
# author:xc
# datetime:2018/8/27 10:56

from app import util
from . import html
from flask import request
from dbConnection.MysqlConn import Mysql
from app.MySession import MySession
import time


# 获取验证码
@html.route('/api/get/code', methods=['POST', 'GET'])
def api_get_code():
    phone = request.values.get('phone')
    flag = request.values.get('flag')
    if int(flag) == 0:  # 注册
        mysql = Mysql()
        is_exist = mysql.getOne("SELECT * FROM girl_teacher WHERE phone = %s " % phone, None)
        if is_exist:
            code = util.CODE_EXIST
        else:
            sms_id = 147675
            code = util.jg_send_sms(phone, sms_id)
        mysql.dispose()
    elif int(flag) == 1:
        mysql = Mysql()
        is_exist = mysql.getOne("SELECT * FROM girl_teacher WHERE phone = %s " % phone, None)
        if is_exist:
            sms_id = 147675
            code = util.jg_send_sms(phone, sms_id)
        else:
            code = util.CODE_FAIL
        mysql.dispose()
    else:
        sms_id = 147675
        code = util.jg_send_sms(phone, sms_id)
    data = {
        'code': code
    }
    return util.to_json(data)


# 忘记密码
@html.route('/api/update/password', methods=['POST', 'GET'])
def api_update_password():
    try:
        phone = request.values.get('phone')
        code = request.values.get('code')

        is_verify = util.verify_code(phone, code)
        if is_verify != util.CODE_SUCCESS:
            data = {
                'code': util.CODE_FAIL,
                'msg': u"验证码不正确"
            }
            return util.to_json(data)
        password = request.values.get('password')
        sql = "update girl_teacher set password='%s' where phone='%s'" % (
            util.md5(str(password) + util.LOGIN_KEY), phone)
        mysql = Mysql()
        res = mysql.update(sql, None)
        mysql.dispose()
        if res > 0:
            code = util.CODE_SUCCESS
            msg = u'修改成功'
    except Exception as e:
        print e
        code = util.CODE_ERROR
        msg = u'服务器内部错误'
    data = {
        'code': code,
        'msg': msg
    }
    return util.to_json(data)


@html.route('/api/set/password', methods=['POST'])
@util.verify_login
def api_set_password(uid):
    try:
        password = request.values.get('password')
        sql = "update girl_teacher set password='%s' where uid='%s'" % (
            util.md5(str(password) + util.LOGIN_KEY), uid)
        mysql = Mysql()
        res = mysql.update(sql, None)
        mysql.dispose()
        code = util.CODE_FAIL
        msg = u'密码已设置'
        if res > 0:
            code = util.CODE_SUCCESS
            msg = u'修改成功'
    except Exception as e:
        print e
        code = util.CODE_ERROR
        msg = u'服务器内部错误'
    data = {
        'code': code,
        'msg': msg
    }
    return util.to_json(data)


# 快速登录
@html.route('/api/quick/login', methods=['POST', 'GET'])
def api_quick_login():
    phone = request.values.get('phone')
    code = request.values.get('code')
    is_verify = util.verify_code(phone, code)
    if is_verify != util.CODE_SUCCESS:
        data = {
            'code': util.CODE_FAIL,
            'msg': u"验证码不正确"
        }
        return util.to_json(data)
    mysql = Mysql()
    sql = "select * from girl_teacher where phone ='%s'" % phone
    result = mysql.getOne(sql, None)
    if result:
        data = {
            'code': util.CODE_SUCCESS,
            "session": MySession.create_session(str(result['uid']))
        }
        mysql.dispose()
        return util.to_json(data)
    else:
        insert_sql = "INSERT INTO girl_teacher (phone,nickName,username,registerTime,registerIp) " \
                     "values ('%s','%s','%s','%s','%s')" % (
                         phone, phone, phone, util.int_day(int(time.time())), util.get_current_ip())
        uid = mysql.insertOne(sql=insert_sql, value=None)
        mysql.dispose()
        if uid > 0:
            session = MySession.create_session(str(uid))
            code = util.CODE_SUCCESS
        else:
            session = ""
            code = util.CODE_FAIL
        data = {
            'code': code,
            'session': session
        }
        return util.to_json(data)


# 注册
@html.route('/api/user/register', methods=['POST', 'GET'])
def api_user_register():
    phone = request.values.get('phone')
    code = request.values.get('code')
    is_verify = util.verify_code(phone, code)
    if is_verify != util.CODE_SUCCESS:
        data = {
            'code': util.CODE_FAIL,
            'msg': u"验证码不正确"
        }
        return util.to_json(data)
    password = request.values.get("password")
    nickname = request.values.get("nickname", default="")
    mysql = Mysql()
    is_exist = mysql.getOne("SELECT * FROM girl_teacher WHERE phone = %s " % phone, None)
    if is_exist is None:
        sql = "INSERT INTO girl_teacher (username,nickname,phone,password,registerTime,registerIp)" \
              " values ('%s','%s','%s','%s','%s','%s')" % (
                  phone, nickname, phone, util.md5(str(password) + util.LOGIN_KEY), util.int_day(int(time.time())),
                  util.get_current_ip())
        result = mysql.insertOne(sql, None)
        if result > 0:
            code = util.CODE_SUCCESS
            msg = u'注册成功'
        else:
            code = util.CODE_FAIL
            msg = u'注册失败'
    else:
        code = util.CODE_EXIST
        msg = u'账号已存在'
    mysql.dispose()
    data = {
        'code': code,
        'msg': msg
    }
    return util.to_json(data)


# 用户登录
@html.route('/api/user/login', methods=['POST', 'GET'])
def api_user_login():
    phone = request.values.get("phone")
    password = request.values.get("password")
    mysql = Mysql()
    sql = "SELECT * FROM girl_teacher WHERE phone = '%s' AND password = '%s'" % (
        phone, util.md5(str(password) + util.LOGIN_KEY))
    result = mysql.getOne(sql, None)
    if result is not None:
        if result["status"] == 1:
            code = util.CODE_SUCCESS
            update_sql = "UPDATE girl_teacher SET loginNum = loginNum + 1 , " \
                         "loginTime = '%s',loginIp ='%s' WHERE uid = '%s' " % (
                             util.int_day(int(time.time())), util.get_current_ip(), result["uid"])
            mysql.update(update_sql, None)
            session = MySession.create_session(str(result["uid"]))
        else:
            code = util.CODE_FAIL
            session = ""
    else:
        code = util.CODE_FAIL
        session = ""
    data = {
        'code': code,
        'session': session
    }
    return util.to_json(data)



